import React, { useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { defaultSearchConfig } from '@/defaultColConfig';
import { buildBooleanMap } from '@/utils/mapUtil';
import { AutoComplete, Input, Radio, Layout, Button } from 'antd';
import type { RegisterUnitloadsArgs, RegisterUnitloadsInfo } from '@/models/loc';
import moment from 'moment';
import { ConnectProps, connect } from 'umi';
import { ConnectState } from '@/models/connect';
import { CurrentUser } from '@/models/user';
import { getOrderCodeAuthComplete, getDestinationAuthComplete, checkPalletCode, checkQrcode, getWorkordersToQrcode, postPalletAndDestination, postPalletize } from '@/services/unitload';


export interface GlobalHeaderRightProps extends Partial<ConnectProps> {
  currentUser?: CurrentUser;
  menu?: boolean;
}

class RegisterUnitloads extends React.Component<GlobalHeaderRightProps> {
    constructor(props: GlobalHeaderRightProps | Readonly<GlobalHeaderRightProps>) {
      super(props);
      console.log(this.props);
    }

    state = {
      orderCodeOption: [],
      destinationOption: [],
      setOptions: [],
      destinationValue: "",
      palletType: "",
      palletCode: "",
      orderCode: "",
      materialBarcode: "",
      palletCodeDisabled: false,
      proTableList: [],
      rowKey: "",
    };

    getDefaultTime = () => {
        return moment(new Date()).subtract(15, 'minutes');
    }

    /**
     * 单号筛选
     * @param changeInfo
     */
    changeForOrderCode = (changeInfo: any) => {
      getOrderCodeAuthComplete(changeInfo).then(ret => {
        if (ret.success) {
          let result: any = [];
          ret.data?.forEach((item) => {
            result.push({value : item.jobNo});
          })
          this.setState({
            orderCodeOption: result,
            orderCode: changeInfo,
          })
        }
      });
    }
    
    selectForOrderCode = (selectInfo: any) => {
      console.log(selectInfo)
    }

    onSearchForOrderCode = (searchInfo: any) => {
      console.log(searchInfo)
    }

    /**
     * 目的点
     * @returns 
     */

    changeForDestination = (changeInfo: any) => {
      this.setState({
        destinationValue: changeInfo
      })
    }
    
    selectForDestination = (selectInfo: any) => {
      console.log(selectInfo)
    }

    onSearchForDestination = (searchInfo: any) => {
      console.log(searchInfo)
    }

    postDestination = (searchInfo: any) => {
      console.log(searchInfo)
      console.log(this.state.palletType)
      postPalletAndDestination(this.state.palletType, searchInfo).then((res) => {

      })
    }

    palletTypeFilter = (value: any) => {
      getDestinationAuthComplete(value).then((res) => {
        console.log(res)
        if(res.success){
          const result = [];
          res.data?.forEach((item) => {
            result.push({value: item.locationCode});
          })
          this.setState({
            destinationOption: result
          })
        }
      })
      this.setState({
        palletType: value
      })
    }

    render(): React.ReactNode {
      const {
        currentUser = {
          name: '',
        },
      } = this.props;

      const { Search } = Input;
  
      const columns: ProColumns<RegisterUnitloadsArgs>[] = [
          {
            title: '入库工单',
            dataIndex: 'orderCode',
            hideInTable: true,
            renderFormItem: () => {
              return <AutoComplete
              options={this.state.orderCodeOption}
              style={{ width: 200 }}
              allowClear={true}
              onSelect={this.selectForOrderCode}
              onSearch={this.onSearchForOrderCode}
              onChange={this.changeForOrderCode}
              placeholder="请输入入库工单"
            />
            },
          },
          {
            title: '入库类型',
            dataIndex: 'warehousingType',
            hideInTable: true,
            valueType: 'radioButton',
            valueEnum: buildBooleanMap('全部', '生产入库', '非生产入库'),
            initialValue: '',
          },
          {
            title: '入库人',
            dataIndex: 'warehouser',
            hideInTable: true,
            initialValue: currentUser.name,
          },
          {
            title: '入库日期',
            dataIndex: 'warehousingDate',
            hideInTable: true,
            valueType: 'date',
            initialValue: this.getDefaultTime(),
          },
          {
            title: '托盘类型',
            dataIndex: 'palletType',
            hideInTable: true,
            renderFormItem: () => {
              return <Radio.Group defaultValue='小托盘'>
                       <Radio.Button onClick={() => this.palletTypeFilter('小号托盘')} value="小托盘">小托盘</Radio.Button>
                       <Radio.Button onClick={() => this.palletTypeFilter('中号托盘')} value="中托盘">中托盘</Radio.Button>
                       <Radio.Button onClick={() => this.palletTypeFilter('大号托盘')} value="大托盘">大托盘</Radio.Button>
                     </Radio.Group>
            }
          },
          {
            title: '目的点',
            dataIndex: 'destination',
            hideInTable: true,
            initialValue: '',
            renderFormItem: () => {
              return <AutoComplete
              options={this.state.destinationOption}
              style={{ width: 200 }}
              onSelect={this.selectForDestination}
              onSearch={this.onSearchForDestination}
              onChange={this.changeForDestination}
              value={this.state.destinationValue}
              placeholder=""
            >
              <Search allowClear={true} placeholder="请输入目的点" onSearch={this.postDestination} enterButton="呼叫" />
            </AutoComplete>
            },
          },
          {
            title: '托盘号',
            dataIndex: 'palletCode',
            hideInTable: true,
            renderFormItem: () => {
              return <Input
                placeholder="请输入托盘号"
                allowClear={true}
                disabled={this.state.palletCodeDisabled}
                onChange={(e) => {this.setState({palletCode: e.target.value})}}
                onPressEnter={(e) => {
                  checkPalletCode(e.target.value).then((res) => {
                    if(res.success){
                      this.setState({
                        palletCodeDisabled: true
                      })
                    }
                  })
                }}
              />
            },
          },
          {
            title: '物料条码',
            dataIndex: 'materialBarcode',
            hideInTable: true,
            initialValue: '',
            renderFormItem: () => {
              return <Input
                placeholder="请输入物料条码"
                allowClear={true}
                value={this.state.materialBarcode}
                onChange={(e) => {this.setState({materialBarcode: e.target.value})}}
                onPressEnter={(e) => {
                  const qrCode = e.target.value;
                  checkQrcode(qrCode).then((res) => {
                    if(res.success){
                      getWorkordersToQrcode(qrCode, this.state.orderCode).then((res) => {
                        if(res.success){
                          let proTableList:any = [];
                          let index = 0;
                          this.state.proTableList.forEach(item => {
                            proTableList.push({...item, index: index});
                            index ++;
                          })
                          res.data?.forEach(item => {
                            proTableList.push({...item, index: index, qrCode: qrCode});
                            index ++;
                          })
                          this.setState({
                            proTableList: proTableList,
                            materialBarcode: ""
                          })
                        }
                      })
                    }
                  })
                }}
              />
            },
          },

          // 列表字段
          {
            title: '物料编码',
            dataIndex: 'materialCode',
            search: false,
            initialValue: '',
          },
          {
            title: '物料名称',
            dataIndex: 'description',
            search: false,
            initialValue: '',
          },
          {
            title: '图号',
            dataIndex: 'drawingNo',
            search: false,
            initialValue: '',
          },
          {
            title: '套数',
            dataIndex: 'comment',
            search: false,
            initialValue: '',
          },
          {
            title: '数量',
            dataIndex: 'comment2',
            search: false,
            initialValue: '',
          },
          {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
              <>
                <Button type="primary" onClick={(e) => {
                  let result: any = [];
                  let index = 0;
                  this.state.proTableList.forEach((item) => {
                    if(item.index != record.index)
                    {
                      result.push({...item, index: index});
                      index ++;
                    }
                  })
                  this.setState({
                    proTableList: result
                  })
                }}>
                  删除
                </Button>
                </>
             )
          },
      ];

      return (
          <PageContainer>
              <ProTable<RegisterUnitloadsInfo, RegisterUnitloadsArgs>
                headerTitle="注册货载"
                rowKey={this.state.rowKey}
                search={defaultSearchConfig}
                toolBarRender={() => []}
                dataSource={this.state.proTableList}
                columns={columns}
                bordered
              />

            <Layout.Footer style={{background: "#FFF", marginTop: "20px", textAlign: "right"}}>
              <Button size="large">取消</Button>
              <Button type="primary" size="large" style={{marginLeft: "20px"}} onClick={(e) => {
                postPalletize(this.state.orderCode, this.state.palletCode, this.state.proTableList).then((res) => {
                  if(res.success){
                    location.reload();
                  }
                })
              }}>提交</Button>
            </Layout.Footer>

          </PageContainer>
        );
      }
}


export default connect(({ user, global, loading }: ConnectState) => ({
    currentUser: user.currentUser,
    collapsed: global.collapsed,
    fetchingMoreNotices: loading.effects['global/fetchMoreNotices'],
    fetchingNotices: loading.effects['global/fetchNotices'],
    notices: global.notices,
}))(RegisterUnitloads);